<template>
  <div class="stats-container">
    <div class="stats-row" v-if="type === 'personnel-map'"> 
      <div class="stats-panel" ref="mapPanel">
        <div class="stats-panel-head stats-form">
          <h3 class="stats-map">
            <span>{{ $t('report.statistics.title38') }}</span>
            <div class="stats-form-group stats-checkbox refresh-checkbox">          
              <el-popover trigger="hover">
                <div>{{$t('report.staffView.tip1')}}</div>         
                <base-checkbox slot="reference" :value="isRefresh" @input="changeRefresh">{{$t('report.staffView.tip2')}}</base-checkbox>     
              </el-popover>
            </div>     
          </h3>
          <biz-team-select multiple is-auto-select-child collapse class="stats-team-select biz-team-select" :value="tag" @input="chooseTeam" :fetch-func="fetchTeam" @remove="clearTeam"/>
          <!-- <div class="stats-form-group">
            <select @change="chooseTeam">
              <option value="">全部</option>
              <option v-for="team in teams" :key="team.id" :value="team.id">{{team.name}}</option>
            </select>
          </div> -->
          <div class="stats-form-group">
            <select @change="chooseState">
              <option value="">{{$t('report.staffView.allState')}}</option>
              <option v-for="state in states" :key="state" :value="state">{{state}}</option>
              <option value="notSetState">{{$t('report.staffView.noSetState')}}</option>
            </select>
          </div>
          <div class="stats-form-group stats-form-group-user">
            <publink-select :value="selectedUser" @input="chooseUser" filterable clearable :placeholder="$t('common.placeholder.selectMember')" class="stats-staff-select">

              <div 
                :class="['user-updata',userType === 'isToday' ? 'active' : '']" 
                @click="choseTab('isToday')"
              >{{ `${$t('common.label.localIsTodayUpdate')}: ${localIsTodayUpdate.length}` }}
              </div>

              <div 
                :class="['user-updata border-bottom',userType === 'notToday' ? 'active' : '']"
                @click="choseTab('notToday')"
              >{{ `${$t('common.label.localNotTodayUpdate')}: ${localNotTodayUpdate.length}` }}
              </div>

              <!-- 没数据时展示 -->
              <div slot="empty" v-if="isShowSelectEmpty" class="empty-cls el-select-dropdown__list">
                <div 
                  :class="['user-updata',userType === 'isToday' ? 'active' : '']" 
                  @click="choseTab('isToday')"
                >{{ `${$t('common.label.localIsTodayUpdate')}: ${localIsTodayUpdate.length}` }}
                </div>

                <div 
                  :class="['user-updata',userType === 'notToday' ? 'active' : '']"
                  @click="choseTab('notToday')"
                >{{ `${$t('common.label.localNotTodayUpdate')}: ${localNotTodayUpdate.length}` }}
                </div>
              </div>

              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.displayName"
                :value="item.userId"
                :origin="item"
              >
              
                <template v-if="isOpenData">
                  <open-data type='userName' :openid="item.staffId"></open-data>
                </template>
              </el-option>
            </publink-select>
            
          </div>
          
          <el-popover trigger="hover" class="popover-tip">
            <div>{{$t('report.staffView.tip3')}}</div>
            <stats-popover-icon slot="reference"></stats-popover-icon>
          </el-popover>
          <el-popover trigger="hover" class="popover-tip">
            <ul>
              <i18n path="report.staffView.tip6" tag="li">
                <kbd place="keyName">ESC</kbd>
              </i18n>
              <li>{{$t('report.staffView.tip4')}}</li>
              <li>{{$t('report.staffView.tip5')}}</li>
            </ul>

            <button slot="reference" type="button" class="stats-fullscreen-btn" @click="fullScreen">
              <i class="iconfont icon-fangda"></i>
            </button>
          </el-popover>
        </div>
        <div class="stats-panel-body">
          <div class="stats-staff-map-wrap" ref="mapWrap">
            <div id="map"></div>

            <div class="stats-staff-map-info" :class="{'stats-staff-map-info-height': isOpen}">
              <div class="stats-staff-map-summary">
                <p>
                  <span><i class="iconfont icon-team"></i></span>
                  <strong>{{$t('common.label.serviceTeam')}}：</strong>
                <span>{{teamName}}</span></p>
                <p>
                  <span><i class="iconfont icon-zhuangtai"></i></span>
                  <strong>{{$t('common.base.status')}}：</strong>
                  <span>{{stateName}}</span>
                </p>

                <p>
                  <span @click="isOpen = !isOpen" class="total-open">
                    <i class="iconfont" :class="{'icon-sum': isOpen, 'icon-caret-right': !isOpen}"></i>
                  </span>
                  <strong>{{$t('common.zhongqi.total')}}：</strong>
                  <span>{{teamUsers.length}}</span>{{ $t('common.base.people') }}
                </p>
              </div>
              <transition name="slide-fade">
              <div v-if="isOpen" class="stats-staff-map-state-panel">
                <div v-for="state in states" :key="state" class="stats-staff-state-row">
                  <div class="stats-staff-state-badge" :style="{backgroundColor: stateColorMap[state]}"></div>
                  <div><strong>{{state}}：</strong> {{teamUserStateMap[state] || 0}}{{ $t('common.base.people') }} </div>
                </div>
                <div class="stats-staff-state-row">
                  <div class="stats-staff-state-badge" :style="{backgroundColor: '#000'}"></div>
                  <div><strong>{{$t('report.common.noSetState')}}：</strong> {{teamUserStateMap['notSetState'] || 0}}{{ $t('common.base.people') }} </div>
                </div>
              </div>
              </transition>
            </div>

            <div ref="mapInfo" v-show="showInfoWindow" class="stats-staff-window">
              <div class="stats-staff-window-head">
                <img :src="head()">
              </div>
              <div class="stats-staff-window-info">
                <h5 class="stats-staff-window-name">
                  <a href="javascript:;" @click="openDetail">
                    <template v-if="isOpenData">
                      <open-data type="userName" :openid="showUser.staffId"></open-data>
                    </template>
                    <template v-else>
                      {{ showUser.displayName }}
                    </template>
                  </a>
                  <button type="button" class="stats-staff-window-close" @click="closeWindow"><i class="iconfont icon-fe-close"></i></button>
                </h5>
                <p>{{$t('report.staffView.label1')}}：<span>{{ dateFormat(showUser.lastLoginTime) }}</span></p>
                <p>{{$t('common.label.unfinishTask')}}：{{showUser.unfinishedTask}} <a href="javascript:;" @click="openDetail" class="pull-right">{{ $t('common.base.view') }}</a></p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="stats-row" v-if="type === 'personnel-statistics'"> 
      <staff-task-table @trackEvent="sttTrackEventHandler" :chart-type="type"></staff-task-table>
    </div>
    
    <div class="stats-row" v-if="type === 'personnel-statistics' || type === 'profit-event'"> 
      <staff-category-chart :evaluate-config="evaluateConfig" @trackEvent="sccTrackEventHandler" :type="type"></staff-category-chart>
    </div>
  </div>
</template>

<script>
import { t } from '@src/locales';
/* global AMap, moment, _init_data*/
import { isOpenData, openAccurateTab } from '@src/util/platform'
import * as DomUtil from 'src/util/dom/index';
import moment from 'moment';
import http from 'src/util/HttpUtil';

import StaffCategoryChart from './StaffCategoryChart.vue';
import StaffTaskTable from './StaffTaskTable.vue';
import BaseCheckbox from 'packages/BaseCheckbox.vue';

import Loading from 'packages/BaseLoading';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

let map = null;
let infoWindow = null;
const DEFAULT_HEAD = '/resource/images/account_userhead.png';
let t1;

//api
import { getProviderNameList } from '@src/api/serviceProviderApi'
import { getUserUnFinishedTask } from '@src/api/ReportApi'
export default {
  name: 'staff-view',
  data(){
    return {
      isOpenData,
      tag: [],

      // teams: [],
      states: [],
      stateColorMap: {},
      evaluateConfig: {},

      teamId: '',
      teamName: t('common.base.all'),
      state: '',
      stateName: t('common.base.all'),
      teamUsers: [],
      teamUserStateMap: {},
      selectedUser: '',

      filterTeamUser: [],

      showInfoWindow: false,
      showUser: {},

      isRefresh:false,
      type: '', // 判断入口
      isOpen: true, // 是否展开
      localIsTodayUpdate:[], //今日已更新定位的集合
      localNotTodayUpdate:[], //今日未更新定位的集合
      userType:'all',
    };
  },

  computed:{
    userList(){
      let list = this.teamUsers;

      switch(this.userType){
        case 'all': list = this.teamUsers;break;
        case 'isToday': list = this.localIsTodayUpdate;break;
        case 'notToday': list = this.localNotTodayUpdate;break;
      }
      return list
    },
    isShowSelectEmpty() {
      return !this.localIsTodayUpdate.length && !this.localNotTodayUpdate.length;
    }
  },

  methods: {
    clearTeam(value = []){
      this.tag = value;
      const ids = []
      value.forEach(item=>{
        ids.push(item.id)  
      })
      this.teamId = ids.join(',');
      this.teamName = (value[0] && value[0].tagName) || this.$t('common.base.all');
      // this.teamId = tag.id || '';
      // this.teamName = tag.tagName || '全部';

      this.renderMap();
    },
    fetchTeam(params){
      return http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    changeRefresh(value){  
      this.isRefresh = value;
      if(!this.isRefresh) return clearInterval(t1);   
      t1 = setInterval(() => {
        this.renderMap();
      }, 300000);      
    },
    choseTab(tab){
      // 当点击的tab和当前选中的是一个tab，此时将取消选中
      if(this.userType === tab){
        this.userType = 'all';
        this.filterTeamUser = this.teamUsers;
      }else{
        this.$set(this,'selectedUser','')
        this.userType = tab;
        this.filterTeamUser = tab === 'isToday' ? this.localIsTodayUpdate : this.localNotTodayUpdate;
      }
      
      this.drawMap();
    },
    chooseUser(value){
      this.$tdOnEvent('pc：人员报表-人员地图人员筛选事件');
      this.selectedUser = value;

      let filterTeamUser = this.teamUsers;

      if(value){
        let user = null;
        for(let i = 0; i < this.teamUsers.length; i++){
          if(this.teamUsers[i].userId == value){
            user = this.teamUsers[i]
            break;
          }
        }

        filterTeamUser = [user];
      }
     
      this.filterTeamUser = filterTeamUser;
      this.drawMap();
    },
    fullScreen(){
      if(this.$platform.inDingTalk()) return;
      
      DomUtil.fullScreen(this.$refs.mapWrap);
    },
    initMap() {
      map = new AMap.Map('map', {
        resizeEnable: true,
        zoom: 4,
        zooms: [4, 18]
      });

      this.renderMap();
    },    
    chooseTeam(value){
      this.$tdOnEvent('pc：人员报表-人员地图团队选择事件');
      // let tag = (Array.isArray(value) ? value[0] : value) || {};
      this.tag = value;
      const ids = []
      value.forEach(item=>{
        ids.push(item.id)  
      })
      this.teamId = ids.join(',');
      this.teamName = (value[0] && value[0].tagName) || this.$t('common.base.all');
      // this.teamId = tag.id || '';
      // this.teamName = tag.tagName || '全部';

      this.renderMap();
      // 部门埋点
      this.type && this.$track.commonFn.chartTrack(this.type, 'REPORT_SEARCH_TEAM', this.$track)
    }, 
    chooseState(event){
      this.$tdOnEvent('pc：人员报表-人员地图工作状态筛选事件')

      let target = event.target;
      let selectedIndex = target.selectedIndex;
      let option = target.options[selectedIndex];
      
      this.state = option.value;
      this.stateName = option.innerHTML;
      this.renderMap();
    }, 
    async renderMap(){
      try {
        let instance = Loading.show(this.$refs.mapPanel);
        let { data: teamUsers } = await this.fetchTeamUser();
        this.teamUsers = teamUsers;
        this.teamUserStateMap = this.buildTeamUserStateMap(teamUsers);

        this.filterTeamUser = teamUsers;
        this.selectedUser = '';
        instance.hide();

        this.drawMap();
        
      } catch (error) {
        console.log(error)
      }
    },
    drawMap(){
      let teamUsers = this.filterTeamUser;

      map.clearMap();
      for(let i = 0; i < teamUsers.length; i++){
        this.createMarker(teamUsers[i])
      }

      infoWindow = new AMap.InfoWindow({
        isCustom: true, // 使用自定义窗体
        autoMove: true,
        content: this.$refs.mapInfo,
        offset: new AMap.Pixel(0, -36),
        closeWhenClickMap: true
      });

      map.setFitView();
    },
    buildTeamUserStateMap(teamUsers = []){
      let map = {};

      //今日已更新定位的集合
      this.localIsTodayUpdate = [];
      //今日未更新定位的集合
      this.localNotTodayUpdate = [];
      teamUsers.length && teamUsers.forEach(user => {
        if(user.localIsTodayUpdate){
          this.localIsTodayUpdate.push(user)
        }else{
          this.localNotTodayUpdate.push(user)
        }

        let state = user.state;  
        if(map['notSetState'] == null) map['notSetState'] = 0;
        if(!state || !this.states.includes(state)) return map['notSetState'] += 1;
        if(map[state] == null) map[state] = 0;
        map[state] += 1;

      })
      return map;
    },
    createMarker(user){
      if(!user.longitude || !user.latitude) return;
      let marker = new AMap.Marker({
        map,
        position: [user.longitude, user.latitude],
        icon: new AMap.Icon({            
          size: new AMap.Size(36, 36), // 图标大小
          image: user.head || DEFAULT_HEAD,
          imageSize: new AMap.Size(36, 36)
        }),
        extData: user  
      });

      let ctx = this;
      marker.on('click', async function(event){
        !ctx.showInfoWindow && (ctx.showInfoWindow = true);
        ctx.showUser = marker.getExtData();

        // 获取未完成工单数量
        const unfinishedTask = await ctx.fetchUserUnFinishedTask(ctx.showUser?.userId);
        ctx.$set(ctx.showUser, 'unfinishedTask', unfinishedTask);
        
        infoWindow.open(map, marker.getPosition());
      })
    },
    loadMap() {
      let callback = '_amap_callback_stats_staff_dongls_0111';
      let url = `https://webapi.amap.com/maps?v=1.3&key=3cf1b829475ac81c406ceca9ec57d73d&callback=${
        callback}`;
      window[callback] = () => {
        setTimeout(() => this.initMap(), 100);
      };
      console.log(DomUtil)
      DomUtil.importScript(url).catch(err => console.log(err));
    },
    fetchTeamUser(){
      let params = {
        teamId: this.teamId,
        state: this.state
      }
      return http.post('/api/dataware/outside/user/staff/teamUser', params);
    },
    head(){
      return this.showUser.head || DEFAULT_HEAD;
    },
    closeWindow(){
      infoWindow && infoWindow.close();
    },
    openDetail(){
      let user = this.showUser || {};
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `userView_${ user.userId}`, 
      //   title: '用户详情', 
      //   close: true, 
      //   url: `/security/user/view/${ user.userId}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityUserView,
        key: user.userId,
        fromId
      })
    },
    // staff-task-table strackEventHandler
    sttTrackEventHandler(type) {
      switch (type) {
      case 'chooseTeam':
        this.$tdOnEvent('pc：人员报表-工单统计团队选择事件');
        break;
      case 'updateServerName':
        this.$tdOnEvent('pc：人员报表-工单统计服务人员输入框事件');
        break;
      case 'chooseColumn':
        this.$tdOnEvent('pc：人员报表-选择列事件');
        break;
      case 'chooseTaskType':
        this.$tdOnEvent('pc：人员报表-选择工单类型事件');
        break;
      default:
        break;
      }
    },
    // staff-category-chart strackEventHandler
    sccTrackEventHandler(type) {
      switch (type) {
      case 'chooseTeam':
        this.$tdOnEvent('pc：人员报表-人员统计团队选择事件');
        break;
      case 'chooseDate':
        this.$tdOnEvent('pc：人员报表-日期选择事件');
        break;
      case this.$t('common.base.task'):
        this.$tdOnEvent('pc：人员报表-工单事件');
        break;
      case this.$t('report.eventScoreChart.label3'):
        this.$tdOnEvent('pc：人员报表-营收事件');
        break;
      case this.$t('common.base.degree'):
        this.$tdOnEvent('pc：人员报表-满意度事件');
        break;
      case this.$t('report.staffCategoryChart.title9'):
        this.$tdOnEvent('pc：人员报表-效率事件');
        break;                              
      default:
        break;
      }
    },
    // 格式化时间
    dateFormat(date){
      return moment(date).format('YYYY-MM-DD HH:mm');
    },

    // 处理从服务商跳转的条件
    async handlerProvider() {
      try {
        // 服务商跳转过来的
        let engineerCondition = sessionStorage.getItem('engineer_condition')
        if (engineerCondition) {
          let engineerMap = JSON.parse(engineerCondition) || {}
          // 调用接口去查询服务商信息
          let res = await getProviderNameList(engineerMap?.allProvider ? {} : {tenantProviderIds: [engineerMap.providerId]})
          if (res.success) { // 默认所有的服务商
            this.tag = res.data
          }
          const ids = []
          this.tag.forEach(item=>{
            ids.push(item.id)
          })
          this.teamId = ids.join(',');
          this.teamName = (this.tag[0] && this.tag[0].tagName) || this.$t('common.base.all');
          this.renderMap();
        }
      } catch (e) {
        console.error(e)
      } finally {
        sessionStorage.removeItem('engineer_condition')
      }
    },
    // 获取人员未完成工单数量
    async fetchUserUnFinishedTask(userId){
      try {
        const { result } = await getUserUnFinishedTask(userId);
        return Promise.resolve(result);
      }catch(e) {
        console.log('fetchUserUnFinishedTask: ', e);
        return Promise.resolve();
      }
    }
  },
  async mounted(){
    this.type = window.location.href.split('type=')[1]
    let initData = JSON.parse(sessionStorage.getItem('_init_data')) || {}
    // this.teams = initData.teams || [];
    this.states = initData.states || [];
    this.stateColorMap = initData.stateColorMap || {};
    this.evaluateConfig = initData.evaluateConfig || {};
    try {
      await this.handlerProvider();
    } catch (e) {
      console.error(e)
    }
    if(this.type == 'personnel-map') {
      // 加载地图
      this.loadMap();
    }
  },
  components: {
    [StaffCategoryChart.name]: StaffCategoryChart,
    [StaffTaskTable.name]: StaffTaskTable,
    [BaseCheckbox.name]: BaseCheckbox
  }
}
</script>


<style lang="scss">
.stats-map{
  display:flex;
  .refresh-checkbox{
    margin-left:20px;
  }
}

.stats-staff-map-wrap{
  position: relative;
  height: 100%;
  width: 100%;
}

.stats-staff-map-info{
  position: absolute;
  top: 10px;
  right: 10px;
  width: 240px;
  
  border-radius: 2px;
  background-color: #fff;
  box-shadow: 0 2px 2px rgba(0,0,0,.15);
  z-index: 998;

  strong{
    font-weight: 700;
  }
}
.stats-staff-map-info-height {
  height: calc(100% - 60px);
}

.stats-staff-map-summary{
  padding: 5px 8px;
  border-bottom: 1px dashed #DCDCDC;

  p{
    color: #333;
    margin: 0;
    height: 28px;
    line-height: 28px;
    display: flex;
    flex-flow: row nowrap;
    align-items: center;

    span:first-child{
      display: block;
      width: 20px;
      height: 28px;
      text-align: center;
      margin-right: 6px;
    }

    i{
      color: #999;
      font-size: 18px; 
    }
  }

  .total-open {
    cursor: pointer;
  }
}

.stats-staff-map-state-panel{
  background-color: #fafafa;
  padding: 5px 8px;
  height: calc(100% - 95px);
  overflow: auto;
}

.stats-staff-state-row{
  display: flex;
  flex-flow: row nowrap;
  align-items: center;

  line-height: 20px;
  padding: 4px 0;

  .stats-staff-state-badge{
    width: 20px;
    height: 14px;
    border-radius: 2px;
    margin-right: 6px;
  }
}


#map {
  width: 100%;
  height: 100%;
  min-height: calc(100vh - 75px);
}

.stats-staff-window{
  position: relative;
  width: 320px;
  display: flex;
  flex-flow: row nowrap;

  box-shadow: 0 2px 2px rgba(0,0,0,.15);
  background-color: #fff;
  border-radius: 2px;
  padding: 8px;
}

.stats-staff-window-head{
  width: 68px;
  height: 68px;

  img{
    display: block;
    width: 100%;
    height: 100%;
    border-radius: 4px;
  }
}

.stats-staff-window-info{
  flex: 1;
  padding-left: 8px;
  overflow: hidden;

  p{
    margin: 0;
    padding-top: 2px;
    font-size: 13px;
    line-height: 20px;
    color: #666;
  }
}

.stats-staff-window-name{
  position: relative;
  margin: 0;
  line-height: 1;
  height: 24px;
  font-size: 18px;
  font-weight: 400;
  padding-right: 30px;
  overflow: hidden;

  a{
    display: block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}

.stats-staff-window-close{
  position: absolute;
  top: 0;
  right: 0;
  width: 16px;
  height: 16px;
  padding: 0;
  margin: 0;
  background-color: transparent;
  outline: none;
  border: none;
  color: #666;

  &:hover{
    color: #000;
  }
}

.stats-staff-select .el-input__inner{
  height: 24px;
  line-height: 20px !important;
}

.stats-staff-select {
  .el-input{
    & > span.el-input__suffix {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  } 
}

.popover-tip{
    margin-left: 5px;
    display: flex;
    align-items: center;
}

.stats-form-group-user {
  width: 200px;
  .open-data-input,
  .el-select {
    width: 100%;
  }
  
}

</style>
<style lang="scss" scoped>
.user-updata{
  font-size: 14px;
  padding: 0 20px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  height: 34px;
  line-height: 34px;
  box-sizing: border-box;
  cursor: pointer;
  &.active{
    color:$color-primary-light-6;
  }
}
.border-bottom{
  border-bottom:1px dashed #cdcdcd;
}
::v-deep .amap-icon {
  img {
    border-radius: 50%;
  }
}

/* 可以设置不同的进入和离开动画 */
/* 设置持续时间和动画函数 */
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all .1s ease;
}
.slide-fade-enter, .slide-fade-leave-to
/* .slide-fade-leave-active for below version 2.1.8 */ {
  transform: translateY(10px);
  opacity: 0;
}
</style>